package com.irdstudio.apicenter.gateway.web.view;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.irdstudio.apicenter.gateway.comm.MaccsPacket;

public class JsonView extends AbstractView {

	private static final Logger log = LoggerFactory.getLogger(JsonView.class);
	private JsonGenerator jsonGenerator;

	public JsonView(HttpServletRequest request, HttpServletResponse response, MaccsPacket packet) {
		super(request, response, packet);
		try {
			jsonGenerator = new ObjectMapper().getFactory().createGenerator(response.getOutputStream(),
					JsonEncoding.UTF8);
		} catch (Exception e) {
			log.error("", e);
		}
	}

	public void renderView() {
		try {

			jsonGenerator.writeObject(packet.getMap());
			if (packet != null)
				log.info("Result:" + packet.getMap());
		} catch (Exception e) {
			log.error("", e);
		}
	}

	/**
	 * 返回JSON视图下数据(字符串)
	 */
	@Override
	public String getViewData() {
		try {
			return new ObjectMapper().writeValueAsString(packet.getMap());
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getMapData() {
		return packet.getMap();
	}
}
